package com.example.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pojo.PageData;
import com.example.pojo.ResultBean;
import com.example.pojo.SysRole;
import com.example.pojo.SysUserRole;
import com.example.service.ISysRoleService;
import com.example.service.ISysUserRoleService;
import com.example.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author lyj
 * @since 2023-02-16
 */
@RestController
@RequestMapping("/sys-role")
public class SysRoleController {

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    /**
     * 查询全部
     * @return
     */
    @GetMapping("queryAll")
    public ResultBean queryALl(){
        return ResultBean.success(sysRoleService.list());
    }

    /**
     * 给用户分配角色
     * @param map
     * @return
     */
    @PostMapping("/assignRoles")
    public ResultBean assignRoles(@RequestBody Map<String,Object> map){
        System.out.println("分配角色");
        map.forEach((k,v) -> System.out.println(k + ":" + v));
        Object userId = map.get("userId");
        List roleIds = (List) map.get("roleIds");
        boolean rs = sysUserRoleService.assignRoles((Serializable) userId,roleIds);
        return rs ? ResultBean.success() : ResultBean.error();
    }

    /**
     * 分页条件查询
     * @param pageData
     * @param map
     * @return
     */
    @GetMapping("/list")
    public ResultBean list(PageData pageData,@RequestParam Map<String,Object> map){
        Page<RoleVo> page = new Page<>(pageData.getPageNum(),pageData.getPageSize());
        sysRoleService.queryByCondition(page,map);
        return ResultBean.success(page);
    }

    /**
     * 新增或修改
     * @param sysRole
     * @return
     */
    @PostMapping("saveOrUpdate")
    public ResultBean saveOrUpdate(@RequestBody SysRole sysRole){
        System.out.println("新增或更新的数据：" + sysRole);
        boolean rs = sysRoleService.saveOrUpdate(sysRole);
        return rs ? ResultBean.success() : ResultBean.error();
    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id){
        boolean rs = sysRoleService.removeById(id);
        return rs ? ResultBean.success() : ResultBean.error();
    }
}
